﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;
using System.Collections;
using System.Transactions;
using System.Data;

namespace Langben.App.Controllers
{
    /// <summary>
    /// 损溢单表
    /// </summary>
    public class ts_checkController : BaseController
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {
            DateTime dtStart = Convert.ToDateTime("1900-10-10");
            DateTime dtEnd = DateTime.Now;
            string DH = "";
            string YSDH = "";

            if (search != null)
            {
                string[] searchStr = search.Split('^');
                if (searchStr[0].Split('&')[1].ToString() != "")
                {
                    dtStart = Convert.ToDateTime(searchStr[0].Split('&')[1]);
                }
                if (searchStr[1].Split('&')[1].ToString() != "")
                {
                    dtEnd = Convert.ToDateTime(searchStr[1].Split('&')[1]);
                }
                if (searchStr[2].Split('&')[1].ToString() != "")
                {
                    DH = searchStr[2].Split('&')[1];
                }
                if (searchStr[3].Split('&')[1].ToString() != "")
                {
                    YSDH = searchStr[3].Split('&')[1];
                }

            }


            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            ht.Add("@DTStart", dtStart);
            ht.Add("@DTEnd", dtEnd);
            string sqlString = rx.SqlBack("sel_KCPDData");
            string strwhere = "";
            if (DH != "")
            {
                strwhere += " and convert(varchar(20),i_no) like '%'+'" + DH + "'+'%' ";
            }
            if (YSDH != "")
            {
                strwhere += " and c_orgno like '%'+'" + YSDH + "'+'%' ";
            }

            sqlString = sqlString.Replace("@CC", strwhere);
            DataSet ds = rx.DsDoSQL(sqlString, ht);
            List<ts_check> checkList = new List<ts_check>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ts_check check = new ts_check();
                check.Id = dr["Id"].ToString();
                check.i_no = Convert.ToInt32(dr["i_no"].ToString()); 
                check.dt_dt = Convert.ToDateTime(dr["dt_dt"].ToString()); 
                check.c_base = dr["c_base"].ToString(); 
                check.c_agency = dr["c_agency"].ToString();
                check.c_keeper = dr["c_keeper"].ToString();
                check.c_clerk = dr["c_clerk"].ToString();
                check.i_sign = dr["i_sign"].ToString();
                checkList.Add(check);
            }

            return Json(new datagrid
            {
                total = checkList.Count(),
                rows = checkList.Select(s => new
                {
                    Id = s.Id
                            ,
                    i_no = s.i_no
                            ,
                    dt_dt = s.dt_dt
                            ,
                    c_base = s.c_base
                            ,
                    c_agency = s.c_agency
                            ,
                    c_keeper = s.c_keeper
                            ,
                    c_clerk = s.c_clerk
                            ,
                    c_comment = s.c_comment
                            ,
                    i_sign = s.i_sign

                }
                   )
            }); 
            //int total = 0;
            //List<ts_check> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            //return Json(new datagrid
            //{
            //    total = total,
            //    rows = queryData.Select(s => new
            //    {
            //        Id = s.Id
            //        ,i_no = s.i_no
            //        ,dt_dt = s.dt_dt
            //        ,c_base = s.c_base
            //        ,c_agency = s.c_agency
            //        ,c_keeper = s.c_keeper
            //        ,c_clerk = s.c_clerk
            //        ,c_comment = s.c_comment
            //        ,i_sign = s.i_sign
					
            //    }

            //        )
            //});
        }

        //判断是否发生损溢
        public ActionResult CheckIfSY(string search)
        {
            bool resultValue = true;
            string[] rowsInf = search.Split('^');

            for (int i = 0; i < rowsInf.Length - 1; i++)
            {
                string aaad = rowsInf[i];
                object arrayObj;
                arrayObj = new Hashtable();
                arrayObj = JSON.JsonDecode(rowsInf[i]);
                Hashtable ht = (Hashtable)arrayObj;
                Dictionary<string, string> dict = new Dictionary<string, string>();//Dictionary接受Json字符串
                foreach (DictionaryEntry de in ht)
                {
                    if (dict.ContainsKey(de.Key.ToString())) continue;//不能重复啊
                    dict.Add(de.Key.ToString(), de.Value == null ? "" : de.Value.ToString());
                }
                //如果发生损溢则返回false
                if (Convert.ToInt32(dict["f_quant"].ToString()) != Convert.ToInt32(dict["f_quant_check"]))
                {
                    resultValue = false;
                } 
            }
            return Json(new { result = resultValue }, JsonRequestBehavior.AllowGet);
        }

        //改变状态
        public void ChangeState(string search,string sign) 
        {
            ts_check check = new ts_check();
            check.Id = new BLL.ts_checkBLL().GetById(search).Id;
            check.i_no = new BLL.ts_checkBLL().GetById(search).i_no;
            check.dt_dt = new BLL.ts_checkBLL().GetById(search).dt_dt;
            check.c_base = new BLL.ts_checkBLL().GetById(search).c_base;
            check.c_agency = new BLL.ts_checkBLL().GetById(search).c_agency;
            check.c_keeper = new BLL.ts_checkBLL().GetById(search).c_keeper;
            check.c_clerk = new BLL.ts_checkBLL().GetById(search).c_clerk;
            check.c_comment = new BLL.ts_checkBLL().GetById(search).c_comment;
            check.i_sign = sign;
            m_BLL.Edit(ref validationErrors, check);
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            ts_check item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        {
            if (m_BLL.GetAll().Count() > 0)
            {
                ViewData["DH"] = m_BLL.GetAll().OrderByDescending(o => o.i_no).First().i_no + 1;
            }
            else
            {
                ViewData["DH"] = 1;
            }
            ViewData["person"] = GetCurrentPerson();
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(ts_check entity)
        {
            string checkID="";
            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    //if (entity != null && ModelState.IsValid)
                    //{
                    string currentPerson = GetCurrentPerson();
                    //entity.CreateTime = DateTime.Now;
                    //entity.CreatePerson = currentPerson;

                    entity.Id = Result.GetNewId();
                    checkID = entity.Id;
                    string returnValue = string.Empty;
                    if (m_BLL.Create(ref validationErrors, entity))
                    {
                        //LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，入库表的信息的Id为" + entity.Id, "入库表"
                        //    );//写入日志 
                        //return Json(Suggestion.InsertSucceed);
                    }
                    else
                    {
                        if (validationErrors != null && validationErrors.Count > 0)
                        {
                            validationErrors.All(a =>
                            {
                                returnValue += a.ErrorMessage;
                                return true;
                            });
                        }
                        LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，库存盘点表的信息，" + returnValue, "库存盘点表"
                            );//写入日志                      
                        return Json(new { Id = checkID }, Suggestion.InsertFail + returnValue); //提示插入失败
                    }

                    if (entity.GoodsDetail != null)
                    {
                        string[] rowsInf = entity.GoodsDetail.Split('^');

                        for (int i = 0; i < rowsInf.Length - 1; i++)
                        {
                            string aaad = rowsInf[i];
                            object arrayObj;
                            arrayObj = new Hashtable();
                            arrayObj = JSON.JsonDecode(rowsInf[i]);
                            Hashtable ht = (Hashtable)arrayObj;
                            Dictionary<string, string> dict = new Dictionary<string, string>();//Dictionary接受Json字符串
                            foreach (DictionaryEntry de in ht)
                            {
                                if (dict.ContainsKey(de.Key.ToString())) continue;//不能重复啊
                                dict.Add(de.Key.ToString(), de.Value == null ? "" : de.Value.ToString());
                            }

                            ts_checkdetail checkdetail = new ts_checkdetail();
                            ts_checkdetailBLL tbtb = new ts_checkdetailBLL();
                            checkdetail.Id = Result.GetNewId(); 
                            checkdetail.i_no = entity.Id;
                            checkdetail.i_num = i + 1;
                            checkdetail.c_code = dict["c_code"].GetString();
                            checkdetail.f_quant = Convert.ToDecimal(dict["f_quant"].GetString());
                            checkdetail.f_quant_check = Convert.ToDecimal(dict["f_quant_check"].GetString());
                            checkdetail.c_comment = dict["c_comment"].GetString();

                            tbtb.Create(ref validationErrors, checkdetail);

                        }
                        transactionScope.Complete();
                        LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，库存盘点表的信息Id为" + entity.Id + "的商品信息", "库存盘点商品表");//写入日志 
                        return Json(new { Id = checkID }, Suggestion.InsertSucceed);
                    }
                    transactionScope.Complete();
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，库存盘点表的信息Id为" + entity.Id, "库存盘点表"
                           );//写入日志 
                    return Json(new { Id = checkID }, Suggestion.InsertSucceed);
                    //}
                }
                catch
                {
                    Transaction.Current.Rollback();
                }
            } 
            return Json(new { Id = checkID }, Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            ts_check item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, ts_check entity)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    //if (entity != null && ModelState.IsValid)
                    //{
                    string[] parentId = { entity.Id };
                    new ts_checkdetailBLL().DeleteCollectionByParent(ref validationErrors, parentId);
                    string currentPerson = GetCurrentPerson();
                    //entity.CreateTime = DateTime.Now;
                    //entity.CreatePerson = currentPerson;

                    string returnValue = string.Empty;
                    if (m_BLL.Edit(ref validationErrors, entity))
                    {
                        //LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，入库表的信息的Id为" + entity.Id, "入库表"
                        //    );//写入日志 
                        //return Json(Suggestion.InsertSucceed);
                    }
                    else
                    {
                        if (validationErrors != null && validationErrors.Count > 0)
                        {
                            validationErrors.All(a =>
                            {
                                returnValue += a.ErrorMessage;
                                return true;
                            });
                        }
                        LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，库存盘点表的信息，" + returnValue, "库存盘点表"
                            );//写入日志                      
                        return Json(Suggestion.InsertFail + returnValue); //提示插入失败
                    }

                    if (entity.GoodsDetail != null)
                    {
                        string[] rowsInf = entity.GoodsDetail.Split('^');

                        for (int i = 0; i < rowsInf.Length - 1; i++)
                        {
                            string aaad = rowsInf[i];
                            object arrayObj;
                            arrayObj = new Hashtable();
                            arrayObj = JSON.JsonDecode(rowsInf[i]);
                            Hashtable ht = (Hashtable)arrayObj;
                            Dictionary<string, string> dict = new Dictionary<string, string>();//Dictionary接受Json字符串
                            foreach (DictionaryEntry de in ht)
                            {
                                if (dict.ContainsKey(de.Key.ToString())) continue;//不能重复啊
                                dict.Add(de.Key.ToString(), de.Value == null ? "" : de.Value.ToString());
                            }

                            ts_checkdetail checkdetail = new ts_checkdetail();
                            ts_checkdetailBLL tbtb = new ts_checkdetailBLL();
                            checkdetail.Id = Result.GetNewId();
                            checkdetail.i_no = entity.Id;
                            checkdetail.i_num = i + 1;
                            checkdetail.c_code = dict["c_code"].GetString();
                            checkdetail.f_quant = Convert.ToDecimal(dict["f_quant"].GetString());
                            checkdetail.f_quant_check = Convert.ToDecimal(dict["f_quant_check"].GetString());
                            checkdetail.c_comment = dict["c_comment"].GetString();

                            tbtb.Create(ref validationErrors, checkdetail); 

                        }
                        transactionScope.Complete();
                        LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，库存盘点表的信息Id为" + entity.Id + "的商品信息", "库存盘点商品表");//写入日志 
                        return Json(Suggestion.InsertSucceed);
                    }
                    transactionScope.Complete();
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed + "，库存盘点表的信息Id为" + entity.Id, "库存盘点表"
                           );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                    //}
                }
                catch
                {
                    Transaction.Current.Rollback();
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.Its_checkBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public ts_checkController()
            : this(new ts_checkBLL()) { }

        public ts_checkController(ts_checkBLL bll)
        {
            m_BLL = bll;
        }
        
    }
}


